<?php
require "././vendor/autoload.php";

use \PhpAmqpLib\Connection\AMQPStreamConnection;
use \PhpAmqpLib\Exchange\AMQPExchangeType;
use \PhpAmqpLib\Message\AMQPMessage;

$host = PHP_OS == "Linux" ? "127.0.0.1" : "10.0.0.200";

$queueName = "workQueue";
$exchangeName = "workExchange";
$routeKey = "workRouteKey";

$con = new AMQPStreamConnection('10.0.0.200', '5672', 'wyqgg', '123456');
$ch = $con->channel();

$ch->confirm_select();

$ch->set_ack_handler(function (AMQPMessage $message) {
    echo "消息发送成功!---------" . $message->getBody().PHP_EOL;
});

$ch->set_nack_handler(function (AMQPMessage $message) {
    echo "消息发送失败!---------" . $message->getBody().PHP_EOL;
});

$ch->set_return_listener(function ($replyCode, $replyText, $exchangeName, $routeKey, AMQPMessage $message) {
    echo "消息投递失败".$replyCode . PHP_EOL . $replyText . PHP_EOL . $exchangeName . PHP_EOL . $routeKey . PHP_EOL . $message->body . PHP_EOL;
//    echo "消息投递失败!--------" . $message->getBody() . PHP_EOL;
});

//$ch->exchange_declare($exchangeName, AMQPExchangeType::DIRECT, false, true, false);

//$ch->queue_declare($queueName, false, true, false, false);

//$ch->queue_bind($queueName, $exchangeName, $routeKey);


//发送消息
$pro = ['delivery_mode' => AMQPMessage::DELIVERY_MODE_PERSISTENT];
for ($i = 1; $i < 100; $i++) {
    $messageBody = "workMessage";
    $message = new AMQPMessage($messageBody, $pro);
    $ch->basic_publish($message, $exchangeName, $routeKey,true);//mandatory : true 开启消息找不到队列return
    $ch->wait_for_pending_acks_returns(); //开启后confirm和return机制都开启
}

$ch->close();
$con->close();